package cn.chencaiju.day12;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SynchorizedTest {
	/**
	 * 多线程使用同一资源
	 * @param args
	 */
	public static void main(String[] args) {
		Counter counter=new Counter();
		ExecutorService service=Executors.newFixedThreadPool(5);
		for(int i=0;i<10;i++) {
			service.execute(new CounterRunnable(counter));
		}
		//主线程延迟，确保子线程执行完
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(counter.getCount());
		service.shutdown();
	}
}

/**
 * 自定义线程启动方法
 * @author haiming
 *
 */
class CounterRunnable implements Runnable{
	private Counter c;
	public CounterRunnable(Counter c) {
		this.c=c;
	}
	@Override
	public void run() {
		c.count();
	}
	
}

class Counter{
	private int count=0;

	//资源锁，对普通方法同步
	public synchronized void count() {
		setCount(getCount()+1);
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
	
}